import { MessagePlugin } from 'tdesign-vue';

import request from './axios';
import { BASE_URL, TIME_OUT } from './config';
import type { requestConfig } from './types';

import store from '@/store';

/**
 * 请求对象
 */
const newRequest = new request({
  baseURL: BASE_URL,
  timeout: TIME_OUT,
  withCredentials: true,
  interceptors: {
    requestInterceptor(config: requestConfig) {
      config.headers.Authorization = `Bearer ${store.getters['user/token']}`;
      store.commit('setting/toggleLoadingStatus', true);
      return config;
    },
    responseInterceptor(res: any) {
      store.commit('setting/toggleLoadingStatus', false);
      if (!res.data) {
        MessagePlugin.error('请求失败！');
        return;
      }
      if (res.data.code !== 200) {
        MessagePlugin.error(res.data.message);
        return { code: res.data.code, message: res.data.message, info: res.data.data, isError: true };
      }
      return res.data;
    },
    responseInterceptorCatch() {
      store.commit('setting/toggleLoadingStatus', false);
      MessagePlugin.error('请求失败！');
    },
  },
});

export default newRequest;
